import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken,setToken } from '@/utils/auth'
import { isHttp, isPathMatch } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'



NProgress.configure({ showSpinner: false })

// const whiteList = ['/login', '/register','/sso-callback','/error']

const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}
const whiteList = ['/login', '/register', '/error', '/404', '/401','/sso-callback']
// 配置门户登录地址（可配置）
const PORTAL_LOGIN_URL = import.meta.env.VITE_APP_PORTAL_LOGIN_URL
const APP_ID = import.meta.env.VITE_APP_ID 

router.beforeEach(async (to, from, next) => {
  NProgress.start()
   
  const userStore = useUserStore()
  
  // 1. 处理SSO回调（优先处理token）
   // 1. 处理SSO回调（优先处理token）
  if (to.path === '/sso-callback' && to.query.token) {
    try {
      const userStore = useUserStore()
      
      // 先设置token到cookie和store
      setToken(to.query.token)
      userStore.token = to.query.token
      
      // 获取用户信息
      await userStore.getInfo()
      
      // 生成路由
      const accessRoutes = await usePermissionStore().generateRoutes()
      accessRoutes.forEach(route => router.addRoute(route))
      // 优先使用redirect_uri，其次使用redirect参数，最后默认'/'
      let redirectPath = '/'
      if (to.query.redirect_uri) {
        try {
          // 处理完整URL或纯路径两种情况
          const uri = decodeURIComponent(to.query.redirect_uri)
          redirectPath = uri.startsWith('http') ? new URL(uri).pathname : uri
        } catch (e) {
          console.error('redirect_uri解析失败:', e)
          redirectPath = to.query.redirect || '/'
        }
      } else if (to.query.redirect) {
        redirectPath = to.query.redirect
      }
      
      // 验证路径有效性（防止开放重定向）
      if (/^\/[a-zA-Z0-9-_\/]*$/.test(redirectPath)) {
        next(redirectPath)  // 关键修改：直接跳转到目标路径
      } else {
        next('/')
      }
      return
    } catch (error) {
      userStore.logOut()
      next(`/error?msg=${encodeURIComponent(error)}`)
      return
    }
  }

  // 2. 正常路由逻辑
  if (userStore.token) {
    if (to.path === '/login') {
      next('/')
    } else if (userStore.roles.length === 0) {
      try {
        await userStore.getInfo()
        const accessRoutes = await usePermissionStore().generateRoutes()
        accessRoutes.forEach(route => router.addRoute(route))
               next({ ...to, replace: true })
      } catch (error) {
        await userStore.logOut()
        // next(`/login?redirect=${to.path}`)
           const redirectUrl = `${PORTAL_LOGIN_URL}?redirect_uri=${encodeURIComponent(window.location.origin + to.fullPath)}&client_id=${APP_ID}`
      window.location.href = redirectUrl
      }
    } else {
      next()
    }
  } else {
    // isWhiteList(to.path) ? next() : next(`/login?redirect=${to.path}`)
    debugger
     const redirectUrl = `${PORTAL_LOGIN_URL}?redirect_uri=${encodeURIComponent(window.location.origin + to.fullPath)}&client_id=${APP_ID}`
      window.location.href = redirectUrl
  }
})
router.afterEach(() => {
  NProgress.done()
})
